<template>
  <main-card-admin :title="pageTitle" :crumbs="crumbs" :show-screen-space="false">
    <template #default>
      <div class="pageBox">
        <div class="tabBox">
          <div
            v-if="isApi(versionInfo.operateMethodTypes)"
            :class="['tab', activeTab == TYPE.api && 'tab--active']"
            @click="onTabChange(TYPE.api)"
          >
            API
          </div>
          <div
            v-if="isSdk(versionInfo.operateMethodTypes)"
            :class="['tab', activeTab == TYPE.sdk && 'tab--active']"
            @click="onTabChange(TYPE.sdk)"
          >
            SDK
          </div>
        </div>
        <div class="tableBox">
          <a-table
            v-if="activeTab === TYPE.api"
            :style="{ width: '100%' }"
            :pagination="false"
            :columns="tableColumnsAPI"
            :data-source="apiList"
            :loading="tableLoading"
            class="header-right-angle admin-table"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex == 'tools'">
                <!-- 待删除 status===0 -->
                <!-- 待停用 status===3 -->
                <div v-if="record.status === 0 || record.status === 3">
                  <a-button size="small" class="operationBtn" disabled>启用</a-button>
                </div>
                <!-- 待启用 status===2 -->
                <div v-else-if="record.status === 2">
                  <a-button size="small" class="operationBtn" disabled>停用</a-button>
                </div>
                <!-- 运行中 status===1 -->
                <div v-else-if="record.status === 1">
                  <a-button v-auth="'algo-service-start-stop-API'" size="small" class="operationBtn" @click="openModal('disable', record)">
                    停用
                  </a-button>
                </div>
                <!-- 已停用 status===4 -->
                <div v-else-if="record.status === 4">
                  <a-button v-auth="'algo-service-start-stop-API'" size="small" class="operationBtn" @click="openModal('enable', record)">
                    启用
                  </a-button>
                </div>
              </template>
              <template v-else-if="column.dataIndex == 'status'">
                <a-tooltip v-if="record.status == 0 || record.status == 2 || record.status == 3" placement="bottom">
                  <template #title>
                    <span>{{ statusList[record.status]?.name?.substring(1) }}时间 {{ record?.statusTime || '' }}</span>
                  </template>
                  <div :class="['table__status', record.status === 4 && 'error']">{{ statusList[record.status]?.name || '' }}</div>
                </a-tooltip>
                <div v-else :class="['table__status', record.status === 4 && 'error']">{{ statusList[record.status]?.name || '' }}</div>
              </template>
            </template>
          </a-table>
          <a-table
            v-else-if="activeTab === TYPE.sdk"
            :style="{ width: '100%' }"
            :pagination="false"
            :columns="tableColumnsSDK"
            :data-source="sdkList"
            :loading="tableLoading"
            class="header-right-angle admin-table"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex == 'activationTypeName'">
                {{ record?.activationTypeName?.join('/') }}
              </template>
              <template v-else-if="column.dataIndex == 'status'">
                <a-tooltip v-if="record.status == 0 || record.status == 2 || record.status == 3" placement="bottom">
                  <template #title>
                    <span>{{ statusList[record.status]?.name?.substring(1) }}时间 {{ record?.statusTime || '' }}</span>
                  </template>
                  {{ statusList[record.status]?.name || '' }}
                </a-tooltip>
                <span v-else>{{ statusList[record.status]?.name || '' }}</span>
              </template>
              <template v-if="column.dataIndex == 'tools'">
                <a-tooltip placement="bottom">
                  <template #title>
                    <span>下载</span>
                  </template>
                  <a-button v-auth="'algo-version-sdk-down'" type="link" @click="handleDownLoad(record)">
                    <i class="iconfont icon-download-2-line"></i>
                  </a-button>
                </a-tooltip>
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </template>
  </main-card-admin>

  <!-- 启停弹窗 -->
  <timer-modal
    v-model:open="visibleObj.visible"
    :title="`确定${visibleObj.type === 'enable' ? '启用' : '停用'}`"
    :info="`此服务将会被${visibleObj.type === 'enable' ? '启用' : '停用'}，请确认操作！`"
    :date-label="`请选择${visibleObj.type === 'enable' ? '启用' : '停用'}时间*`"
    :ok-text="(visibleObj.type === 'enable' ? '启用' : '停用') + '并发送通知'"
    @ok="onModelOk"
  />
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import { computed, onMounted, reactive, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute } from 'vue-router'

  import { checkKey } from '@/directives/auth'
  import { algoDepotApi, fetchDownload } from '@/services/api'
  import { waitLoading } from '@/utils'
  import { filterTableColumns } from '@/utils/ant-component'

  import TimerModal from '../components/timer-modal.vue'
  import { statusList } from '../options'

  enum TYPE {
    api = '1',
    sdk = '2'
  }
  type StatusType = 'enable' | 'disable'
  const route = useRoute()
  const { id } = route.params as any
  const { detailId } = route.query as any
  const activeTab = ref<TYPE>(TYPE.api)
  const visibleObj = reactive<{ visible: boolean; type: StatusType; id?: string }>({ visible: false, type: 'enable' })

  onMounted(() => {
    getVersionInfo(id)
  })

  const pageTitle = computed(() => {
    return `版本详情（${versionInfo?.value?.algorithmName || ''}-${versionInfo?.value?.versionName || ''}）`
  })
  const crumbs = computed(() => {
    return [
      { path: '/admin/algo-service-manage/list', name: '算法仓库' },
      { path: `/admin/algo-service-manage/detail/${detailId}`, name: `${versionInfo?.value?.algorithmName || ''}` },
      { path: route.path, name: `版本详情（${versionInfo?.value?.algorithmName || ''}-${versionInfo?.value?.versionName || ''}）` }
    ]
  })
  const tableColumnsSDK = reactive(
    filterTableColumns([
      {
        title: '平台',
        dataIndex: 'platformName'
      },
      {
        title: '语言',
        dataIndex: 'languageName',
        width: 200
      },
      {
        title: '授权方式',
        dataIndex: 'activationTypeName',
        width: 200
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 200
      },
      {
        title: '',
        width: 200,
        dataIndex: 'tools',
        align: 'right'
      }
    ])
  )
  const tableColumnsAPI = reactive(
    filterTableColumns([
      {
        title: '算法ID',
        dataIndex: 'id'
      },
      {
        title: '服务状态',
        dataIndex: 'status',
        width: 200
      },
      {
        title: '最大QPS',
        dataIndex: 'qps',
        width: 89
      },
      {
        title: '',
        width: 200,
        dataIndex: 'tools',
        align: 'right'
      }
    ])
  )

  // 获取算法/版本信息
  const versionInfo = ref<any>({})
  const { runAsync: getVersionInfo } = useRequest<ResponseData<any>>(algoDepotApi.getVersionInfo, {
    onSuccess: ({ data }) => {
      versionInfo.value = data
      if (isApi(data.operateMethodTypes)) {
        getVersionList(id, TYPE.api)
      } else {
        activeTab.value = TYPE.sdk
      }
      if (isSdk(data.operateMethodTypes)) {
        getVersionList(id, TYPE.sdk)
      }
    }
  })

  // 获取使用方式
  const apiList = ref<any[]>([])
  const sdkList = ref<any[]>([])

  const { loading: tableLoading, runAsync: runGetVersionList } = useRequest<ResponseData<any>>(algoDepotApi.getVersionList)
  const getVersionList = async (id: string, type: TYPE) => {
    const { data } = await runGetVersionList({ id, type })

    if (type === TYPE.api) {
      apiList.value = data
    }
    if (type === TYPE.sdk) {
      sdkList.value = data
    }
  }

  const isApi = (operateMethodTypes: any) => {
    return (operateMethodTypes?.length === 1 && operateMethodTypes[0] === 1) || operateMethodTypes?.length === 2
  }
  const isSdk = (operateMethodTypes: any) => {
    return (operateMethodTypes?.length === 1 && operateMethodTypes[0] === 2) || operateMethodTypes?.length === 2
  }

  // 切换Tab
  const onTabChange = (type: TYPE) => {
    if (activeTab.value === type) {
      return false
    }
    activeTab.value = type
    if (type === TYPE.api) {
      getVersionList(id, TYPE.api)
    }
    if (type === TYPE.sdk) {
      getVersionList(id, TYPE.sdk)
    }
  }

  // 下载
  const handleDownLoad = async (row: any) => {
    if (!row.sdkServiceUrl) {
      return message.error('文件不存在')
    }

    const url = row.sdkServiceUrl.replace(/\\/g, '/')
    const { data } = await algoDepotApi.downloadSdk(row.id, url)

    waitLoading(fetchDownload(data, row.sdkServiceName), {
      loadingText: '数据准备中,请耐心等待...',
      errorText: '文件下载失败',
      successText: '文件下载成功'
    })
  }

  // TODO: 操作启停
  const openModal = async (type: StatusType, row: any) => {
    if (!checkKey('algo-service-start-stop-API')) {
      return message.warning('暂无权限')
    }
    visibleObj.visible = true
    visibleObj.type = type
    visibleObj.id = row.id
  }

  // 确认启停
  const { runAsync: runVersionDisable } = useRequest(algoDepotApi.versionDisable, {
    onSuccess: () => {
      message.success('操作成功')
      getVersionList(id, TYPE.api)
      visibleObj.visible = false
    }
  })
  const { runAsync: runVersionEnable } = useRequest(algoDepotApi.versionEnable, {
    onSuccess: () => {
      message.success('操作成功')
      getVersionList(id, TYPE.api)
      visibleObj.visible = false
    }
  })
  const onModelOk = async (time: any) => {
    // 停用
    if (visibleObj.type === 'disable') {
      runVersionDisable({ id: visibleObj.id, deletedTime: time })
    }
    // 启用
    else {
      runVersionEnable({ id: visibleObj.id, deletedTime: time })
    }
  }
</script>

<style lang="less" scoped>
  :deep(.ant-modal .ant-modal-body) {
    padding: 26px 34px 16px !important;
  }

  :deep(.ant-btn[disabled]) {
    color: rgba(25, 25, 48, 0.2);
    background: rgba(0, 0, 0, 0.1);
  }

  :deep(.ant-table-container) {
    overflow: hidden;
    border: none !important;
    border-radius: 2px;

    /* border: 1px solid #e8e8eb; */
  }

  .pageBox {
    .tabBox {
      display: flex;
      padding: 12px 0;
      // padding-left: 16px;

      .tab {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 10px;
        width: 90px;
        height: 36px;
        color: rgba(25, 25, 48, 0.45);
        border-radius: 6px;
        cursor: pointer;
        .font18b();

        &--active {
          color: rgba(16, 16, 20, 0.95);
          background: rgba(29, 32, 132, 0.12);
        }
      }
    }

    .tableBox {
      margin-top: 36px;

      .statusBtn {
        display: inline-block;
        padding: 2px 5px;
        line-height: 22px;
        border: 1px solid rgba(0, 0, 0, 0.05);
        border-radius: 6px;
      }
    }
  }
</style>
./options @/types
